#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
创建融资融券相关数据库表
"""

import pymysql
from db_config import DBConfig

def create_margin_tables():
    """创建融资融券相关的数据库表"""

    # 读取SQL文件
    sql_file_path = '../db/stock_margin.sql'

    try:
        with open(sql_file_path, 'r', encoding='utf-8') as f:
            sql_content = f.read()
    except FileNotFoundError:
        print(f"错误：找不到SQL文件 {sql_file_path}")
        return False
    except Exception as e:
        print(f"读取SQL文件失败: {e}")
        return False

    # 分割SQL语句（按分号分割）
    sql_statements = [stmt.strip() for stmt in sql_content.split(';') if stmt.strip()]

    # 连接数据库
    conn = None
    try:
        conn = DBConfig.get_connection()
        cursor = conn.cursor()

        # 执行每个SQL语句
        for i, sql in enumerate(sql_statements, 1):
            if sql:  # 跳过空语句
                try:
                    print(f"执行第 {i} 个SQL语句...")
                    cursor.execute(sql)
                    print(f"[成功] SQL语句 {i} 执行成功")
                except Exception as e:
                    print(f"[失败] SQL语句 {i} 执行失败: {e}")
                    # 继续执行其他语句

        # 提交事务
        conn.commit()
        print("\n[完成] 所有融资融券数据库表创建完成！")

        # 验证表是否创建成功
        cursor.execute("SHOW TABLES LIKE 'stock_margin%'")
        tables = cursor.fetchall()
        print(f"\n创建的表: {[table['Tables_in_stock (stock_margin%)'] for table in tables]}")

        return True

    except Exception as e:
        print(f"数据库操作失败: {e}")
        if conn:
            conn.rollback()
        return False

    finally:
        if conn:
            conn.close()

if __name__ == "__main__":
    print("开始创建融资融券数据库表...")
    success = create_margin_tables()
    if success:
        print("融资融券数据库表创建成功！")
    else:
        print("融资融券数据库表创建失败！")